package util.io;


import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Properties;

/**
 * Created by Administrator on 2017/5/18.
 */
public class FtpUtil {
    static Logger log = LoggerFactory.getLogger(FtpUtil.class);
    private static Properties properties = null;
    private static String userName;
    private static String password;
    private static String ftpAddress;
    private static String baseWorkPath;
    private static int port;
    private static FTPClient ftpClient = new FTPClient();

    static {
        properties = new Properties();
        InputStream is = ResourcesUtilBase.getResourceAsStream("config/properties/ftp.properties");
        try {
            properties.load(is);
        } catch (Exception e) {
            log.error("读取ftp配置文件出现异常");
        }


        userName = properties.getProperty("userName");
        password = properties.getProperty("password");
        ftpAddress = properties.getProperty("ftpAddress");
        baseWorkPath = properties.getProperty("baseWorkPath");
        port = Integer.parseInt(properties.getProperty("port"));
    }

    public static void initFtpClient() throws IOException {
        ftpClient.connect(ftpAddress, port);
        if (ftpClient.login(userName, password) == false) {
            try {
                ftpClient.disconnect();
            } catch (Exception e) {
                log.error("【Manual】=>{}", "登录失败啊");
                throw new RuntimeException("ftp 登录失败啊");
            }
        }

    }




    /**
     * 通过相对路径上传文件
     *
     * @param local               文件输入流
     * @param relativePathAndName  相对路径+文件名
     * @return
     */
    public static boolean saveFileByRelativePath(InputStream local, String relativePathAndName) {
        if (relativePathAndName == null || relativePathAndName.equals("")) {
            return false;
        }
        String fileName = relativePathAndName.substring(relativePathAndName.lastIndexOf("\\") + 1);
        String relativePath = relativePathAndName.substring(0, relativePathAndName.lastIndexOf("\\"));
        return saveFileByRelativePath(local, relativePath, fileName);
    }

    /**
     * 通过相对路径上传文件
     *
     * @param local        文件输入流
     * @param relativePath 相对路径
     * @param fileName  文件名
     * @return
     */
    public static boolean saveFileByRelativePath(InputStream local, String relativePath, String fileName) {
        String absolutePath = baseWorkPath;
        if (!relativePath.startsWith("\\")) {
            absolutePath = absolutePath + "\\";
        }
        absolutePath = absolutePath + relativePath;
        return saveFileByAbsolutePath(local, absolutePath, fileName);
    }




    /**
     * 通过绝对路径上传文件
     * @param local  文件输入流
     * @param absolutePath  绝对路径
     * @param fileName 文件名
     * @return
     */
    public static boolean saveFileByAbsolutePath(InputStream local, String absolutePath, String fileName) {
        try {
            initFtpClient();
            // 设置PassiveMode传输
            ftpClient.enterLocalPassiveMode();
            // 设置以二进制流的方式传输
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //创建目录，当目录不存在时创建
            ftpClient.makeDirectory(absolutePath);
            //工作目录
            ftpClient.changeWorkingDirectory(absolutePath);


            ftpClient.storeFile(new String(fileName.getBytes("utf-8"), "iso-8859-1"), local);
            ftpClient.logout();
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        } finally {
            try {
                local.close();
            } catch (Exception e) {
                log.error("【Manual】=>{}", e.getMessage());
            }
            if (ftpClient != null) {
                try {
                    ftpClient.disconnect();
                } catch (Exception e) {
                    log.error("【Manual】=>{}", e.getMessage());
                }
            }
        }
        return true;
    }


    /**
     * 通过相对路径下载文件
     *
     * @param local               文件输出流
     * @param relativePathAndName  相对路径+文件名
     * @return
     */
    public static boolean getFileFromRelativePath(OutputStream local, String relativePathAndName) {
        if (relativePathAndName == null || relativePathAndName.equals("")) {
            return false;
        }
        String fileName = relativePathAndName.substring(relativePathAndName.lastIndexOf("\\") + 1);
        String relativePath = relativePathAndName.substring(0, relativePathAndName.lastIndexOf("\\"));
        return getFileFromRelativePath(local, relativePath, fileName);
    }

    /**
     * 通过相对路径下载文件
     *
     * @param local        文件输出流
     * @param relativePath 相对路径
     * @param fileName  文件名
     * @return
     */
    public static boolean getFileFromRelativePath(OutputStream local, String relativePath, String fileName) {
        String absolutePath = baseWorkPath;
        if (!relativePath.startsWith("\\")) {
            absolutePath = absolutePath + "\\";
        }
        absolutePath = absolutePath + relativePath;
        return getFileFromAbsolutePath(local, absolutePath, fileName);
    }

    /**
     * 通过绝对路径下载文件
     *
     * @param local        文件输出流
     * @param absolutePath 绝对路径
     * @param fileName 文件名
     * @return
     */
    public static boolean getFileFromAbsolutePath(OutputStream local, String absolutePath, String fileName) {
        boolean flag = false;

        try {
            initFtpClient();
            //指定要下载的目录
            ftpClient.changeWorkingDirectory(absolutePath);
            //遍历下载的目录
            FTPFile[] fs = ftpClient.listFiles();
            for (FTPFile ff : fs) {
                String fname = new String(ff.getName().getBytes("iso-8859-1"), "utf8");
                if (fname.equals(fileName)) {
                    ftpClient.retrieveFile(ff.getName(), local);
                    flag = true;
                }
            }
            ftpClient.logout();
        } catch (Exception e) {
            return flag;
        } finally {
            try {
                local.close();
            } catch (Exception e) {
                log.warn("【Manual】=>{}", e.getMessage());
            }
            if (ftpClient != null) {
                try {
                    ftpClient.disconnect();
                } catch (Exception e) {
                    log.warn("【Manual】=>{}", e.getMessage());
                }
            }
        }
        return flag;
    }



    public static void main(String[] args) throws Exception {

        saveFileByAbsolutePath(new FileInputStream("c:\\jdbc.properties"),baseWorkPath+"11"+"\\","wen2");
    }

}
